package com.hyacinth.lotterysystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyacinth.lotterysystem.dao.entity.PrizeDO;
import com.hyacinth.lotterysystem.dao.mapper.PrizeMapper;
import com.hyacinth.lotterysystem.dto.req.CreatePrizeReq;
import com.hyacinth.lotterysystem.dto.req.PrizeListReq;
import com.hyacinth.lotterysystem.dto.resp.PrizeListResp;
import com.hyacinth.lotterysystem.dto.resp.PrizeNameListResp;
import com.hyacinth.lotterysystem.service.PictureService;
import com.hyacinth.lotterysystem.service.PrizeService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class PrizeServiceImpl extends ServiceImpl<PrizeMapper, PrizeDO> implements PrizeService {
    @Resource
    private PictureService pictureService;
    @Resource
    private PrizeMapper prizeMapper;

    @Override
    public Long createPrize(CreatePrizeReq param, MultipartFile file) {
        // 上传图片
        String fileName = pictureService.savePicture(file);

        // 添加到数据库中
        PrizeDO prizeDO = new PrizeDO();
        BeanUtils.copyProperties(param, prizeDO);
        prizeDO.setImageUrl(fileName);
        prizeMapper.insert(prizeDO);
        Long id = prizeDO.getId();
        return id;
    }

    @Override
    public IPage<PrizeListResp> selectPrizeList(PrizeListReq req) {
        if (req == null)
            req = new PrizeListReq();
        Page<PrizeDO> prizeDOPage = new Page<>(req.getCurrentPage(), req.getPageSize());
        LambdaQueryWrapper<PrizeDO> queryWrapper = Wrappers.lambdaQuery(PrizeDO.class)
                .orderByDesc(PrizeDO::getId);
        prizeDOPage = prizeMapper.selectPage(prizeDOPage, queryWrapper);
        return prizeDOPage.convert(PrizeDO -> {
            PrizeListResp resp = new PrizeListResp();
            BeanUtils.copyProperties(PrizeDO, resp);
            return resp;
        });
    }

    @Override
    public PrizeNameListResp selectPrizeNameList() {
        LambdaQueryWrapper<PrizeDO> prizeDOLambdaQueryWrapper = Wrappers.lambdaQuery(PrizeDO.class)
                .select(PrizeDO::getName);
        List<String> nameList = prizeMapper.selectPrizeNameList();
        PrizeNameListResp prizeNameListResp = new PrizeNameListResp();
        prizeNameListResp.setNameList(nameList);
        return prizeNameListResp;
    }
}
